Passing Arguments
C# Supports to pass the parameters in three ways they are
Call by Value
1) When then formal arguments are modified, if modifications are not reflected on actual arguments then that concept is called as call by value.
Call by Reference: (ref)
1) When then formal arguments are modified, if modifications are reflected on actual arguments then that concept is called as call by reference.
Program on Call by reference
using System;
class abc
{
public void put(ref int x)
{
Console.WriteLine("Value of x" + x);
x = 80;
}
}
class sample
{
public static void Main()
{
int a = 10;
abc x = new abc();
x.put(ref a);
Console.WriteLine("After CAll by refernce" + a);
}
}
Program to find the Factorial value using call by reference
using System;
class abc
{
public void fact(int x,ref int f)
{
while (x >= 1)
{
f = f * x;
x--;
}
}
}
class sample
{
public static void Main()
{
int f = 1,a;
Console.WriteLine("Enter number");
a = Convert.ToInt32(Console.ReadLine());
abc x = new abc();
x.fact(a,ref f);
Console.WriteLine("Factorial value" + f);
}
}
Out parameter
Program on out parameter
using System;
class abc
{
public void put(int x,int y,out int z)
{
z=x+y;
}
}
class sample
{
public static void Main()
{
int a,b,c;
Console.WriteLine ("Enter 2 numbers");
a=Convert.ToInt32 (Console.ReadLine ());
b=Convert.ToInt32 (Console.ReadLine ());
abc x=new abc();
x.put (a,b,out c);
Console.WriteLine ("Sum"+c);
}
}
Program on Array as a parameter
using System;
class abc
{
public void put(int [] x)
{
for (int i = 0; i < x.GetLength(0) ; i++)
{
Console.WriteLine(x[i]);
x[i] = x[i] * 2;
}
}
}
class sample
{
public static void Main()
{
int []a={10,20,30,40};
abc x=new abc ();
x.put(a);
Console.WriteLine();
foreach (int k in a)
Console.WriteLine (k);
}
}